package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.GroupData;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.Item;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.UserOrderLimitDot;
import com.tbvtc.agriculturalcreditchainserver2025.entity.*;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CartMapper;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.TestMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICropService;
import com.tbvtc.agriculturalcreditchainserver2025.service.ITestService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbvtc.agriculturalcreditchainserver2025.service.IUserAddressService;
import com.tbvtc.agriculturalcreditchainserver2025.service.IUserService;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.CartAddressVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.addressItem;
import com.tbvtc.agriculturalcreditchainserver2025.vo.ConsumerVo.PlaceOrderVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 测试order表 服务实现类
 * </p>
 *
 * @author syh
 * @since 2025-04-18
 */
@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, Test> implements ITestService {
    @Resource
    private ICropService cropService;
    @Resource
    private IUserService userService;
    @Resource
    private CartMapper cartMapper;
    @Resource
    private ICropService iCropService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserAddressService userAddressService;


    @Override
    public List<GroupData> findOrderById(UserOrderLimitDot userOrderLimitDot) {
        User user = userService.getById(userOrderLimitDot.getId());
        List<Test> list = list(new LambdaQueryWrapper<Test>()
                .eq(Test::getPhone, user.getPhone())
                .eq(userOrderLimitDot.getStatus() != null, Test::getState, userOrderLimitDot.getStatus())
        );
        List<GroupData> groupList = new ArrayList<>();
        list.forEach(test -> {
            GroupData groupData = BeanUtil.copyProperties(test, GroupData.class);
            Crop crop = cropService.getById(test.getGoodId());
            Item item = BeanUtil.copyProperties(crop, Item.class);
            item.setNum(test.getNum());
            groupData.setItems(List.of(item));
            groupList.add(groupData);
        });
        List<GroupData> endList = new ArrayList<>();
        Map<String, List<GroupData>> collect = groupList.stream().collect(Collectors.groupingBy(GroupData::getOrderId));
        collect.entrySet().forEach(entry -> {
            GroupData groupData = entry.getValue().get(0);
            groupData.setItems(entry.getValue().stream().
                    map(GroupData::getItems)
                    .flatMap(List::stream).
                    collect(Collectors.toList())
            );
            endList.add(groupData);
        });
        return endList;
    }

    @Override
    public List<GroupData> findOrderByConsumerId(UserOrderLimitDot userOrderLimitDot) {
        List<Test> list = list(new LambdaQueryWrapper<Test>()
                .eq(Test::getUserId, userOrderLimitDot.getId())
                .eq(userOrderLimitDot.getStatus() != null, Test::getState, userOrderLimitDot.getStatus())
        );
        List<GroupData> groupList = new ArrayList<>();
        list.forEach(test -> {
            GroupData groupData = BeanUtil.copyProperties(test, GroupData.class);
            Crop crop = cropService.getById(test.getGoodId());
            Item item = BeanUtil.copyProperties(crop, Item.class);
            item.setNum(test.getNum());
            groupData.setItems(List.of(item));
            groupList.add(groupData);
        });
        List<GroupData> endList = new ArrayList<>();
        Map<String, List<GroupData>> collect = groupList.stream().collect(Collectors.groupingBy(GroupData::getOrderId));
        collect.entrySet().forEach(entry -> {
            GroupData groupData = entry.getValue().get(0);
            groupData.setItems(entry.getValue().stream().
                    map(GroupData::getItems)
                    .flatMap(List::stream).
                    collect(Collectors.toList())
            );
            endList.add(groupData);
        });
        return endList;
    }


    @Override
    public IPage<GroupData> findOrderByIdPage(UserOrderLimitDot userOrderLimitDot) {
        // 1. 获取用户信息（不变）
        User user = userService.getById(userOrderLimitDot.getId());
        if (user == null) {
            return new Page<>(); // 若用户不存在，返回空分页
        }

        // 2. 构建分页对象（页码默认1，每页条数默认10，可根据实际调整）
        int pageNum = userOrderLimitDot.getPageNum() == null ? 1 : userOrderLimitDot.getPageNum();
        int pageSize = userOrderLimitDot.getPageSize() == null ? 10 : userOrderLimitDot.getPageSize();
        Page<Test> page = new Page<>(pageNum, pageSize);

        // 3. 分页查询Test表数据（替换原来的list查询）
        IPage<Test> testPage = this.page(page, new LambdaQueryWrapper<Test>()
                .eq(Test::getPhone, user.getPhone())
                .eq(userOrderLimitDot.getStatus() != null, Test::getState, userOrderLimitDot.getStatus())
        );

        // 4. 处理分页结果：将Test转换为GroupData并分组（核心逻辑不变，仅基于分页后的list处理）
        List<Test> pageList = testPage.getRecords(); // 分页后的当前页数据
        List<GroupData> groupList = new ArrayList<>();
        pageList.forEach(test -> {
            GroupData groupData = BeanUtil.copyProperties(test, GroupData.class);
            Crop crop = cropService.getById(test.getGoodId());
            Item item = BeanUtil.copyProperties(crop, Item.class);
            item.setNum(test.getNum());
            groupData.setItems(List.of(item));
            groupList.add(groupData);
        });

        // 5. 按orderId分组，合并items（逻辑不变）
        List<GroupData> endList = new ArrayList<>();
        Map<String, List<GroupData>> collect = groupList.stream()
                .collect(Collectors.groupingBy(GroupData::getOrderId));
        collect.entrySet().forEach(entry -> {
            GroupData groupData = entry.getValue().get(0);
            groupData.setItems(entry.getValue().stream()
                    .map(GroupData::getItems)
                    .flatMap(List::stream)
                    .collect(Collectors.toList())
            );
            endList.add(groupData);
        });

        // 6. 构建分页结果：用原分页的总条数、页码等信息，封装处理后的list
        Page<GroupData> resultPage = new Page<>();
        resultPage.setRecords(endList); // 当前页的分组数据
        resultPage.setTotal(testPage.getTotal()); // 总条数（基于Test表的总记录数）
        resultPage.setCurrent(testPage.getCurrent()); // 当前页码
        resultPage.setSize(testPage.getSize()); // 每页条数
        resultPage.setPages(testPage.getPages()); // 总页数

        return resultPage;
    }


    @Override
    public String buy(PlaceOrderVo placeOrderVo) {
        Snowflake snowflake = new Snowflake(1L, 1L); // workerId, datacenterId
        long orderId = snowflake.nextId();
        Test orders = BeanUtil.copyProperties(placeOrderVo, Test.class);
        orders.setGoodId(placeOrderVo.getCropId());
        orders.setState(0);
        orders.setNum(placeOrderVo.getCount());
        orders.setOrderId(String.valueOf(orderId));
        List<addressItem> addressVos = cartMapper.selectAddressByUserId(placeOrderVo.getUserId());
        String address = "";
        for (addressItem addressVo : addressVos) {
            if ("1".equals(addressVo.getIsDefault())) {
                address = addressVo.getAddress();
            }
        }
        orders.setAddress(address);
        orders.setUserId(placeOrderVo.getUserId());

        orders.setUsername(userAddressService.getOne(new LambdaQueryWrapper<UserAddress>()
                .eq(UserAddress::getUserId, placeOrderVo.getUserId())
                .eq(UserAddress::getIsDefault, 1)
        ).getReceiverName());
        orders.setPhone(iCropService.getById(placeOrderVo.getCropId()).getPhone());
        //设置订单时间15分钟，15分钟后自动取消
        stringRedisTemplate.opsForValue().set("order:" + orders.getOrderId(), " ", 15, TimeUnit.MINUTES);
        save(orders);
        return orders.getOrderId();
    }

}
